# routers/device.py
import logging

from fastapi import APIRouter, WebSocket, HTTPException
from fastapi import WebSocketDisconnect

from like.websocket.ai_service import AIChatService
from like.websocket.device_service import DeviceService
from like.websocket.handlers import WebSocketMessageHandler
from like.websocket.manager import ConnectionManager
from typing import List, Dict, Any
import json
from openai import OpenAI

from .device_manager import device_manager
from .messagehandler import MessageHandler
from .schemas import DeviceInfo, BindRequest, UnbindRequest, DevicePlatformBinding, PlatformInfo

router = APIRouter()

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# 设置API路由

# 初始化硅基流动客户端
# 关键步骤：配置 base_url 为硅基流动的端点
client = OpenAI(
    api_key="sk-kszqnhnnrdiupkuwkczeeqcqtgqklmubpqeaibiyeguemsti",
    base_url="https://api.siliconflow.cn/v1"  # 硅基流动的 API 端点
)

# 初始化服务
connection_manager = ConnectionManager()
device_service = DeviceService()
ai_service = AIChatService()
msg_handler = MessageHandler()
message_handler = WebSocketMessageHandler(connection_manager, device_service, ai_service,client,msg_handler)

@router.websocket("/ws/{device_id}")
async def websocket_endpoint(websocket: WebSocket, device_id: str):
    await connection_manager.connect_device(device_id, websocket)

    try:
        while True:
            # 接收消息
            data = await websocket.receive_text()
            message_dict = json.loads(data)

            # 处理消息
            await message_handler.handle_message(device_id, message_dict, websocket)

    except WebSocketDisconnect:
        connection_manager.disconnect_device(device_id)
    except Exception as e:
        #logger.error(f"WebSocket处理错误: {str(e)}")
        connection_manager.disconnect_device(device_id)


# RESTful API 路由
@router.post("/devices/register", response_model=Dict[str, Any])
async def register_device(device_info: DeviceInfo):
    """注册新设备"""
    success = await device_manager.register_device(device_info)
    if success:
        return {"status": "success", "message": "设备注册成功", "device_id": device_info.DeviceId}
    else:
        raise HTTPException(status_code=400, detail="设备注册失败")

@router.get("/devices", response_model=List[DeviceInfo])
async def get_all_devices():
    """获取所有设备信息"""
    return device_manager.get_all_devices()

@router.get("/devices/online", response_model=List[DeviceInfo])
async def get_online_devices():
    """获取在线设备"""
    return device_manager.get_online_devices()

@router.get("/devices/{device_id}", response_model=DeviceInfo)
async def get_device(device_id: str):
    """获取特定设备信息"""
    device = device_manager.get_device_info(device_id)
    if not device:
        raise HTTPException(status_code=404, detail="设备未找到")
    return device

@router.post("/devices/{device_id}/status")
async def update_device_status(device_id: str, is_online: bool, is_used: bool = None):
    """更新设备状态"""
    device_manager.update_device_status(device_id, is_online, is_used)
    return {"status": "success", "message": "设备状态更新成功"}

@router.post("/devices/{device_id}/message")
async def send_message_to_device(device_id: str, message: Dict[str, Any]):
    """向设备发送消息"""
    success = await device_manager.send_to_device(device_id, message)
    if success:
        return {"status": "success", "message": "消息发送成功"}
    else:
        raise HTTPException(status_code=400, detail="消息发送失败")


#创建发送消息的 API 端点
@router.post("/send-to-device/{device_id}")
async def send_message_to_device(device_id: str, message: Dict):
    """
    向指定设备发送消息
    """
    success = await message_handler.send_to_device(device_id, message)

    if success:
        return {
            "status": "success",
            "message": f"消息已发送到设备 {device_id}",
            "device_id": device_id
        }
    else:
        raise HTTPException(
            status_code=404,
            detail=f"设备 {device_id} 未连接或发送失败"
        )


@router.post("/broadcast")
async def broadcast_message(message: Dict, exclude_devices: List[str] = None):
    """
    向所有设备广播消息
    """
    await message_handler.broadcast(message, exclude_devices)
    return {
        "status": "success",
        "message": "广播消息已发送",
        "recipient_count": len(connection_manager.active_device_connections)
    }


@router.get("/connected-devices")
async def get_connected_devices():
    """
    获取所有已连接的设备列表
    """
    return {
        "connected_devices": list(connection_manager.active_device_connections.keys()),
        "count": len(connection_manager.active_device_connections)
    }